package com.soxing.braindata.service.interceptor;

import com.soxing.braindata.common.config.SystemConfig;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 本地调试时跨域配置
@Component
public class CorsFilter implements Filter {
    @Resource
    private SystemConfig systemConfig;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        // 如果是 OPTIONS 请求，直接返回成功状态，并手动设置CORS头
        if (!systemConfig.isNeedLogin() && "OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setHeader("Access-Control-Allow-Origin", "http://192.168.0.102:9528"); // 你的前端地址
            response.setHeader("Access-Control-Allow-Methods", "POST");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setStatus(HttpServletResponse.SC_OK); // 返回 200
            return; // **关键**：直接返回，不再执行后续的过滤器链
        }

        // 如果不是 OPTIONS 请求，继续执行后续的过滤器（包括安全过滤器）
        chain.doFilter(req, res);
    }
}

//import javax.servlet.*;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//
////@Component
//public class CorsFilter implements Filter {
//
//    final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class);
//
//    @Override
//    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
//        HttpServletResponse response = (HttpServletResponse) res;
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
//        response.setHeader("Access-Control-Max-Age", "3600");
//        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
//        System.out.println("*********************************过滤器被使用**************************");
//        chain.doFilter(req, res);
//    }
//
//    @Override
//    public void init(FilterConfig filterConfig) {
//            logger.info("init corsFilter");
//    }
//
//    @Override
//    public void destroy() {}
//
//}